<template>
  <div>
    <div>
      <ele-page
        :key="time"
        v-loading="loading"
        :formConfig="searchConfig"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        header-align="center"
        :getList="getList"
        lazy
        :load="handLoad"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildNodes' }"
        uniqueId="mesProdBomTable"
      ></ele-page>
    </div>
    <ele-form-drawer class="dialog-pack" size="86%" :isLoading="isLoading" v-model="formDataDialog" v-bind="formDescDialog" :request-fn="handleSubmit" :visible.sync="visible" :title="title">
      <template v-slot:materialCode>
        <el-input v-model="formDataDialog.materialCode" readonly :placeholder="$t('mesProdCharacteristic.selectMaterial')">
          <el-button slot="append" :disabled="formDataDialog.id ? true : false" icon="el-icon-search" @click="baseGoodsDialogVisible = true"></el-button>
        </el-input>
      </template>
      <template v-slot:mesProdBomList>
        <el-button style="margin-bottom: 10px;" plain type="primary" @click="addList">
          {{ $t('mesProdBom.addMaterial') }}
        </el-button>

        <ele-table-editor ref="table" v-cnEn :isShowAdd="false" :rules="bomRules" :columns="bomColumns" v-model="formDataDialog.mesProdBomList">
          <!-- 支持插槽 -->
          <template v-slot:bomVersion="{ data }">
            <div>
              <el-select v-model="data.bomVersion" clearable :placeholder="$t('common.select')">
                <el-option v-for="item in data.banbenList" :key="item.bomVersion" :label="item.bomVersion" :value="item.bomVersion"> </el-option>
              </el-select>
            </div>
          </template>
        </ele-table-editor>
      </template>
    </ele-form-drawer>
    <!-- 导入弹框 -->
    <ele-form-drawer
      size="30%"
      :isLoading="isLoadingImport"
      v-model="importData"
      v-bind="importFormDescDialog"
      :request-fn="handleSubmitImport"
      :visible.sync="importVisible"
      :destroyOnClose="true"
      :title="$i18n.t('mesProdBom.importUsers')"
    >
      <template v-slot:file="{ desc, data, field, formData }">
        <!-- 插槽内容有el-form-item组件包裹 -->
        <uploadNoAuto @onchange="upLoadHandleChange" ref="uploadNoAuto" />
      </template>
    </ele-form-drawer>
    <!-- 此组件放到与抽屉平级，理论上不需要修改 -->
    <ele-dialog-table
      :title="$t('mesProdBom.addProduct')"
      width="1000px"
      :visible.sync="baseGoodsDialogVisible"
      :formConfig="baseGoodsSearchDialog"
      :column="baseGoodsDialogColumn"
      @getSelectData="getSelectBaseGoods"
      :getList="pageBcpAndCp"
      :hasFooter="hasBaseGoodsFooter"
    ></ele-dialog-table>

    <ele-dialog-table
      :title="$t('mesProdBom.addMaterial')"
      width="1000px"
      ref="tabledialog"
      :otherParam="{ fexcludeGoodsCode: formDataDialog.materialCode }"
      :visible.sync="bomDialogVisible"
      :formConfig="baseGoodsSearchDialog"
      :column="baseGoodsDialogColumn"
      @getSelectData="getSelectBaseGoodsBoom"
      :getList="pageExclude"
      :hasFooter="true"
    ></ele-dialog-table>
  </div>
</template>

<script>
import EleTableEditor from 'ele-table-editor'
import { pageExclude } from '@/api/process/mesProcessMaterial'

import { operateList, searchConfig, formDescDialog, rowConfig, importFormDescDialog } from './config'
import {
  getList,
  rowCreate,
  rowUpdate,
  rowDel,
  rowDetail,
  getMaterialCodeList,
  getBomStatusList,
  getMaterialTypeValueList,
  getManufactureMethodValueList,
  getTreeList,
  publish,
  stop,
  upgrade
} from '@/api/materials/mesProdBom'
import { baseGoodsDialog } from './mixin'
import { importData } from '@/api/materials/mesProdBom'
import uploadNoAuto from '@/components/upload-no-auto'
export default {
  name: 'mesProdBom',
  mixins: [baseGoodsDialog, formDescDialog],
  components: { EleTableEditor, uploadNoAuto },
  data() {
    return {
      pageExclude,
      time: '',
      bomDialogVisible: false,
      title: null,
      visible: false,
      isLoading: false,
      loading: false,
      formDataDialog: {},
      searchConfig,
      operateList,
      isLoadingImport: false, // 导入数据loading
      importData: {}, //导入数据
      importVisible: false,
      importFormDescDialog, // 导入字段配置
      getList,
      // 列表页字段的绑定配置
      column: [
        {
          type: 'selection',
          fixed: 'left'
        },
        // {
        //   type: "index",
        //   label: "序号",
        // },
        // {
        //   prop: "parentId",
        //   label: "父ID",
        // },
        // {
        //   prop: "ancestors",
        //   label: "祖先id",
        // },
        {
          prop: 'materialCode',
          label: $i18n.t('mesProdBom.materialCode'),
          minWidth: 160,
          fixed: 'left',
          align: 'left',
          showOverflowTooltip: true
          // optionProp: {
          //   value: "materialCode",
          //   label: "materialName",
          // },
          // option: async (data) => {
          //   const list = await getMaterialCodeList();
          //   return list.data.result;
          // },
        },
        {
          prop: 'materialName',
          label: $i18n.t('mesProdBom.materialName'),
          minWidth: 160,
          showOverflowTooltip: true
        },
        {
          prop: 'bomVersion',
          label: $i18n.t('mesProdBom.version'),
          showOverflowTooltip: true
        },
        {
          prop: 'level',
          label: $i18n.t('mesProdBom.BOMLevel'),
          minWidth: 120,
          showOverflowTooltip: true
        },
        {
          prop: 'bomStatus',
          label: $i18n.t('common.status'),
          showOverflowTooltip: true,
          minWidth: 180,
          render: (h, { row }) => {
            let dom = null
            if (row.bomStatus == 1) {
              dom = (
                <el-tag effect="dark" type="success">
                  {$i18n.t('mesProdBom.enable')}
                </el-tag>
              )
            } else if (row.bomStatus == 2) {
              dom = (
                <el-tag effect="dark" type="warning">
                  {$i18n.t('mesProdBom.deactivate')}
                </el-tag>
              )
            } else if (row.bomStatus == 0) {
              dom = (
                <el-tag effect="dark" type="info">
                  {$i18n.t('mesProdBom.wait')}
                </el-tag>
              )
            }

            return dom
          }
          // optionProp: {
          //   value: "value",
          //   label: "description",
          // },
          // option: async (data) => {
          //   const list = await getBomStatusList();
          //   return list.data.result;
          // },
        },
        {
          prop: 'materialTypeValue',
          label: $i18n.t('mesProdBom.materialTypeCode'),
          minWidth: 160,
          showOverflowTooltip: true
          // optionProp: {
          //   value: "value",
          //   label: "description",
          // },
          // option: async (data) => {
          //   const list = await getMaterialTypeValueList();
          //   return list.data.result;
          // },
        },
        {
          prop: 'materialTypeName',
          label: $i18n.t('mesProdBom.materialTypeName'),
          minWidth: 160,
          showOverflowTooltip: true
        },
        // {
        //   prop: "manufactureMethodValue",
        //   label: "制造方式编码",
        //   width: 100,
        //   optionProp: {
        //     value: "value",
        //     label: "description",
        //   },
        //   option: async (data) => {
        //     const list = await getManufactureMethodValueList();
        //     return list.data.result;
        //   },
        // },
        {
          prop: 'manufactureMethodName',
          label: $i18n.t('mesProdBom.manufactureMethodName'),
          minWidth: 200,
          showOverflowTooltip: true
        },
        {
          prop: 'serielsCode',
          label: $i18n.t('mesProdBom.seriesCode'),
          minWidth: 120,
          showOverflowTooltip: true
        },
        {
          prop: 'serielsName',
          label: $i18n.t('mesProdBom.seriesName'),
          minWidth: 100,
          showOverflowTooltip: true
        },
        {
          prop: 'quantity',
          label: $i18n.t('mesProdBom.pieceYardage'),
          showOverflowTooltip: true,
          minWidth: 120
        },
        {
          prop: 'unit',
          label: $i18n.t('mesProdBom.measureUnits'),
          minWidth: 120,
          showOverflowTooltip: true
        },
        {
          prop: 'advancingStockDays',
          label: $i18n.t('mesProdBom.advancingStockDays'),
          minWidth: 200,
          showOverflowTooltip: true
        },
        {
          prop: 'effectiveDate',
          label: $i18n.t('mesProdBom.effectiveDate'),
          minWidth: 120,
          showOverflowTooltip: true
        },
        {
          prop: 'expirationDate',
          label: $i18n.t('mesProdBom.expirationDate'),
          minWidth: 120,
          showOverflowTooltip: true
        },
        // {
        //   prop: "factoryCode",
        //   label: "工厂编码",
        //   minWidth: 120,
        //   showOverflowTooltip: true,
        // },
        // {
        //   prop: "remark",
        //   label: "备注",
        //   showOverflowTooltip: true,
        // },
        {
          prop: 'createByName',
          label: $i18n.t('common.createByName'),
          width: 130,
          showOverflowTooltip: true
        },
        {
          prop: 'createTime',
          label: $i18n.t('common.createTime'),
          width: 170
        },
        {
          prop: 'updateByName',
          label: $i18n.t('common.updateByName'),
          width: 130,
          showOverflowTooltip: true
        },
        {
          prop: 'updateTime',
          label: $i18n.t('common.updateTime'),
          width: 170
        }
        // {
        //   prop: "operate",
        //   label: $i18n.t('common.operation'),
        //   width: 160,
        //   fixed: "right",
        //   render: (h, scope) => {
        //     return (
        //       <ele-row-operation
        //         scope={scope}
        //         rowConfig={rowConfig}
        //         onRowOperate={this.rowOperate}
        //       />
        //     );
        //   },
        // },
      ]
    }
  },
  computed: {},
  methods: {
    async handLoad(tree, treeNode, resolve) {
      let { bomVersion, materialCode, level } = tree
      let res = await getTreeList({ bomVersion, materialCode })

      resolve(
        res.data.result.map((ite) => {
          return {
            ...ite,
            level: Number(level) + 1
            //   id: ite.id + "-" + new Date().getTime(),
          }
        })
      )
    },
    //表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name
      let { id, materialCode } = data.rows[0] || { id: '', materialCode: '' }
      const fnc = {
        add: () => {
          this.disableFields(false)
          this.formDataDialog = {}
          this.visible = true
        },
        edit: () => {
          // let id = row.id.split("-")[0];
          this.disableFields(false)
          this.rowDetail(id)
          this.visible = true
        },
        // deleteBatch: () => {
        //   this.$confirm("此操作将批量删除BOM物料表, 是否继续?", "提示", {
        //     confirmButtonText: "确定",
        //     cancelButtonText: "取消",
        //     type: "warning"
        //   }).then(() => {
        //     const ids = data.rows.map((val) => val.id).join(",")
        //     this.rowDel(ids)
        //   })
        // },
        copy: () => {
          //复制

          this.disableFields(false)
          this.rowDetail(data.rows[0].id, 1)
          this.visible = true
        },
        upgrade: () => {
          this.$confirm(`${this.$t('mesProdBom.confirmUpdate')}【${data.rows[0].materialName}】${this.$t('mesProdBom.endMsg')}?`, $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            upgrade({ id, materialCode }).then((res) => {
              this.$message.success($i18n.t('mesProdBom.updateSuccess'))
              this.refresh()
            })
          })
        },
        import: () => {
          this.importDialogData = {}
          this.importVisible = true
        },
        publish: () => {
          this.$confirm(`${this.$t('mesProdBom.confirmPublish')}【${data.rows[0].materialName}】${this.$t('mesProdBom.endMsg')}?`, $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            publish({ id, materialCode }).then((res) => {
              this.$message.success($i18n.t('mesProdBom.publishSuccess'))
              this.refresh()
            })
          })
        },
        deactivate: () => {
          this.$confirm(`${this.$t('mesProdBom.confirmDeactivate')}【${data.rows[0].materialName}】${this.$t('mesProdBom.endMsg')}?`, $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            stop({ id, materialCode }).then((res) => {
              this.$message.success($i18n.t('mesProdBom.deactivateSuccess'))
              this.refresh()
            })
          })
        }
      }
      fnc[data.handleName]()
    },
    //表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name
      let id = row.id
      const fnc = {
        edit: () => {
          // let id = row.id.split("-")[0];
          this.disableFields(false)
          this.rowDetail(id)
          this.visible = true
        },
        detail: () => {
          //   let id = row.id.split("-")[0];
          this.disableFields(true)
          this.rowDetail(id)
          this.visible = true
        }
        // delete: () => {
        //   //  let id = row.id.split("-")[0];
        //   this.$confirm("此操作将删除该BOM物料表, 是否继续?", "提示", {
        //     confirmButtonText: "确定",
        //     cancelButtonText: "取消",
        //     type: "warning",
        //   }).then(() => {
        //     this.rowDel(id);
        //   });
        // },
      }
      fnc[handleName]()
    },
    doSubmit({ title, api, data }) {
      this.isLoading = true
      api(data)
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || title)
          this.visible = false
          // 渲染下级数据
          this.time = new Date().getTime()
          this.refresh()
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    //弹框提交事件
    handleSubmit(data) {
      if (this.isLoading) return // 判断状态
      const params = this.formDataDialog.id ? { title: $i18n.t('common.editSuccess'), api: rowUpdate, data } : { title: $i18n.t('common.addSuccess'), api: rowCreate, data }
      this.doSubmit(params)
    },
    //删除
    // rowDel(data) {
    //   this.loading = true;
    //   rowDel(data)
    //     .then((res) => {
    //       const message = res.data.message;
    //       this.$message.success(message || "删除成功!");
    //       this.refresh();
    //     })
    //     .finally(() => {
    //       this.loading = false;
    //     });
    // },
    disableFields(flag) {
      this.formDescDialog.disabled = flag
      this.formDescDialog.isShowSubmitBtn = !flag
    },
    rowDetail(id, type) {
      rowDetail(id).then((res) => {
        this.formDataDialog = res.data.result
        // 详情版本查询
        this.getBomVersionList(res.data.result.mesProdBomList)
        if (type == 1) {
          this.title = $i18n.t('mesProdBom.copyBOM')
          this.formDataDialog.id = ''
          this.formDataDialog.materialCode = ''
          this.formDataDialog.materialName = ''
        }
      })
    },
    //刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset)
    },
    upLoadHandleChange(file) {
      this.$set(this.importData, 'file', file)
    },
    handleSubmitImport() {
      if (!this.importData.file) {
        this.$message.error($i18n.t('mesProdBom.uploadFile'))
        return
      }
      const formData = new FormData()
      formData.append('file', this.importData.file.get('file'))
      this.isLoadingImport = true
      importData(formData)
        .then((res) => {
          this.$message.success($i18n.t('mesProdBom.wasSuccessful'))
          this.isLoadingImport = false
          this.importVisible = false
          this.refresh()
        })
        .catch((error) => {
          console.log('错误', error)
          this.$set(this.importData, 'file', null)
        })
        .finally(() => {
          this.isLoadingImport = false
          this.$refs.uploadNoAuto.clearFiles()
        })
    }
  }
}
</script>
